package com.youth.framework.security;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.youth.framework.util.MD5Util;

public class MyAuthenticationFilter extends
        UsernamePasswordAuthenticationFilter
{
    private static final String USERNAME = "username";
    
    private static final String PASSWORD = "password";
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
            HttpServletResponse response) throws AuthenticationException
    {
        if (!request.getMethod().equals("POST"))
        {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: "
                            + request.getMethod());
        }
        
        String username = obtainUsername(request);
        String password = obtainPassword(request);
        String validateCode = obtainValidateCode(request);
        
        request.getSession().setAttribute("username", username);
        request.getSession().setAttribute("password", password);
        //request.getSession().setAttribute("validateCode", validateCode);
        
        // 验证用户账号与密码是否正确
        username = username.trim();
        int i = 1;
        try
        {   //password = "c4ca4238a0b923820dcc509a6f75849b";
            password =  MD5Util.MD5(password);
           // i = SystemManager.invoke().queryUsers(username, password);
        }
        catch (Exception e)
        {
            //写日志
        }
        if (i <= 0)
        {
            BadCredentialsException exception = new BadCredentialsException(
                    "用户名或密码不匹配！");
//            request.getSession().setAttribute("errorCode",
//                    ErrorCode.Login.USER_LOGIN_NAME_ERROR);
            throw exception;
        }
        
        // 实现 Authentication
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);
        // 允许子类设置详细属性
        setDetails(request, authRequest);
        
        // 运行UserDetailsService的loadUserByUsername 再次封装Authentication
        return this.getAuthenticationManager().authenticate(authRequest);
    }
    
    @Override
    protected String obtainUsername(HttpServletRequest request)
    {
        try
        {
            
            request.setCharacterEncoding("utf-8");
            Object obj = request.getParameter(USERNAME);
            return null == obj ? "" : obj.toString();
        }
        catch (UnsupportedEncodingException e)
        {
            return null;
        }
    }
    
    @Override
    protected String obtainPassword(HttpServletRequest request)
    {
        Object obj = request.getParameter(PASSWORD);
        return null == obj ? "" : obj.toString();
    }
    
    protected String obtainValidateCode(HttpServletRequest request)
    {
        Object obj = request.getParameter("validateCode");
        return null == obj ? "" : obj.toString();
    }
    
    @Override
    protected void setDetails(HttpServletRequest request,
            UsernamePasswordAuthenticationToken authRequest)
    {
        super.setDetails(request, authRequest);
    }
}
